package com.idea.zd.sys.util.word;

import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 仅支持对docx文件的文本及表格中的内容进行替换
 * 模板仅支持 ${key} 标签
 */
public class WordTemplateHelper {

	private CustomXWPFDocument document;

	public WordTemplateHelper(String tplFilePath) throws IOException{
		this(new File(tplFilePath));
	}

	/**
	 * 初始化模板内容
	 * @param tplFile
	 * @throws IOException
	 */
	public WordTemplateHelper(File tplFile) throws IOException{
		FileInputStream in = new FileInputStream(tplFile);
		document = new CustomXWPFDocument(in);
		IOUtils.closeQuietly(in);
	}

	/**
	 * 初始化模板内容
	 * @param inputStream 模板的读取流(docx文件)
	 * @throws IOException
	 */
	public WordTemplateHelper(InputStream inputStream) throws IOException{
		document = new CustomXWPFDocument(inputStream);
	}

	/**
	 * 替换模板中的标签为实际的内容
	 * @param map
	 */
	public void replaceTag(Map<String,Object> map){
		replaceParagraphs(map);
		replaceTables(map);
	}

	/**
	 * 将处理后的内容写入到输出流中
	 * @param outputStream 输出流
	 * @throws IOException
	 */
	public void write(OutputStream outputStream) throws IOException{
		document.write(outputStream);
	}

	/**
	 * 替换文本中的标签
	 * @param map key(待替换标签)-value(文本内容)
	 */
	private void replaceParagraphs(Map<String,Object> map){
		List<XWPFParagraph> allXWPFParagraphs = new ArrayList<>();
		allXWPFParagraphs.addAll(document.getParagraphs());
		Iterator<XWPFParagraph> it = allXWPFParagraphs.iterator();
		while(it.hasNext()){
			XWPFParagraph XwpfParagrapg = it.next();
			XWPFParagraphHandler XwpfParagrapgUtils = new XWPFParagraphHandler(XwpfParagrapg);
			XwpfParagrapgUtils.replaceAll(map);
		}
	}

	/**
	 * 替换表格中的标签
	 * @param map key(待替换标签)-value(文本内容)
	 */
	private void replaceTables(Map<String,Object> map){
		List<XWPFTable> xwpfTables = document.getTables();
		for(XWPFTable xwpfTable : xwpfTables){
			XWPFTableHandler xwpfTableUtils = new XWPFTableHandler(xwpfTable);
			xwpfTableUtils.replace(map);
		}
	}

	public CustomXWPFDocument getDocument() {
		return document;
	}
}
